package edu.zju.gis.dbfg.model.common;

import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

/**
 * @author Hu
 * @date 2020/1/4
 **/
public class StringOutputStream extends StreamOutput {

    private StringBuffer sb;
    private byte[] bytes;
    private int count;

    public StringOutputStream() {
        this.sb = new StringBuffer();
        this.bytes = new byte[4096];
        this.count = 0;
    }

    @Override
    public void writeByte(byte b) throws IOException {
        this.bytes[count] = b;
        this.count++;
        if (this.count == this.bytes.length + 1) {
            this.flush();
            this.count = 0;
        }
    }

    @Override
    public void writeBytes(byte[] b, int offset, int length) throws IOException {
        for (int i = offset; i < offset + length; i++) {
            this.writeByte(b[offset]);
        }
    }

    @Override
    public void flush() throws IOException {
        char[] chars = new char[this.count];
        for (int i = 0; i < this.count; i++) {
            chars[i] = (char) this.bytes[i];
        }
        this.sb.append(chars);
        this.count = 0;
    }

    @Override
    public void close() throws IOException {
        this.sb = null;
        this.bytes = null;
    }

    @Override
    public void reset() throws IOException {
        this.sb = new StringBuffer();
        this.count = 0;
    }

    public String getString() {
        return this.sb.toString();
    }

}
